package com.gviiii.pprf.netty.event;

import com.gviiii.pprf.netty.NettyMessage;
import com.gviiii.pprf.utils.JsonUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SocketUtils;

import java.nio.CharBuffer;
import java.util.List;

public class EventEncoder extends MessageToMessageEncoder<NettyMessage> {

//    @Override
//    protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf byteBuf) throws Exception {
//        if (msg==null){
//            return;
//        }
//        String encode = JsonUtils.witeStringByObject(msg)+";";
//        ByteBuf buf = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(encode), CharsetUtil.UTF_8);
//        byteBuf.writeBytes(buf);
//    }

    @Override
    protected void encode(ChannelHandlerContext ctx, NettyMessage msg, List<Object> out) throws Exception {
        if (msg == null) {
            return;
        }
        String encode = JsonUtils.witeStringByObject(msg) + ";";
        ByteBuf buf = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(encode), CharsetUtil.UTF_8);
        String body= String.valueOf(msg.getBody());
        String host=body.split("\\:")[0];
        String port=body.split("\\:")[1];
        DatagramPacket datagramPacket=new DatagramPacket(buf, SocketUtils.socketAddress(host,Integer.valueOf(port)));
        out.add(datagramPacket);
    }
}
